#!/usr/bin/python

import os
import re
import pickle

# Defining Actions similar to enum
WRITE, DELETE, APPEND = range( 3 )

# File containing info
FILENAME = "/home/fotis/WorkSpace/syslogStuff/ext4_syslog/analyzer/logdump"
 

# Describing the basics for file Management
#---------------------------------------------------
class File :
#---------------------------------------------------
        

	path = "" # The path of the file
	fileName = "" # The name of the file 
	inode_num = 0 # The number of inode
	total_blocks = 0; # How many blocks are allocated
	data = "a"  # The actual data
	deleted = 0 # We enable this flag if file is marked as deleted
	fd = 0 # File descriptor for saving state file
   
	def __init__ ( self, record ):
		self.path = "Non implemented"
		self.fileName = record['fileName']
		self.inode_num = record['inode']
		self.total_blocks = 0
		self.data = ""
		self.deleted = 0

	def appendData (self,  newData ) :
		print( "Prev Data : ", self.data , "Appending data", newData)
		self.data = self.data + newData
    
	def replaceData (self,  begin , to , data ):
		print ( "Replacing data" )

	def remove (self ) :
		print ( "Removing file " )
		self.data = ""
		self.deleted = 1

	def printInfo (self) :
		print("PATH : ", self.path , " FILENAME : ", self.fileName , " INODE : ", self.inode_num , " TOTAL_BLOCKS : ", self.total_blocks , "  DATA : " , self.data )

	def saveToDisk (self) :
		print("Saving to disk : " , self.fileName )
		fd = open ( self.fileName , "wb" )
		pickle.dump ( self, fd )
		


FILES = {}
#---------------------------------------------------
def findFile ( record ):
#---------------------------------------------------
    try :
	    fileName = record['fileName']
	    fileDesc = ""
	    print ("FILE " , fileName );
	    try :
		    fileDesc = FILES[ fileName ] # if object of the file is found return it

		    # If FILES return keyerror exception ,it means that there is no object
		    # for this file and we have to create it
	    except KeyError :      
		    print("Adding new handler to the file :" , fileName )
		    fileDesc = File( record )
		    FILES[ fileName ] = fileDesc

		    
	    return fileDesc
    except :
	    raise

# This is the part that all the handling is taking place
#---------------------------------------------------
def manageData( action, fileDesc ) :   
#---------------------------------------------------

  action = record['Action']
  print("\nAction : ", action )

  if action == "WRITE" :
    fileDesc.appendData( record['data'] )
    

  if action == "DELETE" :
      print ( "Delete" )
      fileDesc.remove () 
        


# Incremental backup. Every two months we get a copy from files.
# Every two hours this script is running and we update our state
# for the files

# Open file and convert line entries to tuples
#---------------------------------------------------
if __name__ == "__main__" :
#---------------------------------------------------

    try :
	    logFile = open( FILENAME , 'r' )
	    for line in logFile: 
		    record_fields = line.rsplit()

		    try :
			    # Here i should have some extra checks 
			    action = record_fields[0].split(':')[1]
			    fileName = record_fields[1].split(':')[1]
			    inode = record_fields[2].split(':')[1]
			    dataLen = record_fields[3].split(':')[1]
			    dataPos = record_fields[4].split(':')[1]
			    data = record_fields[5].split(':')[1]

		    except :
			    print
			    dataPos = 0
			    data = "sda"

		    # Access to record is done as record['Action']
		    record = {'Action':action , 'fileName':fileName, 'inode':inode, 'dataLen':dataLen , 'dataPos':dataPos, 'data':data }

		    fileDesc = findFile ( record )
		    manageData ( record , fileDesc ) 
	    fileDesc.printInfo ()
	    fileDesc.saveToDisk () 
    except :
	    raise
